package com.yingsheng.bi.hks.repository.dao.service;

import com.yingsheng.bi.hks.basic.enums.EnumConst;
import com.yingsheng.bi.hks.repository.dao.mapper.RolePermissionExtMapper;
import com.yingsheng.bi.hks.repository.dao.po.RolePermissionExt;
import com.yingsheng.bi.hks.repository.redis.SubjectRedisService;
import com.yingsheng.bi.hks.template.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@Repository
public class RolePermissionDaoService implements RunnerDaoService {

    @Autowired
    private SubjectRedisService subjectRedisService;

    @Autowired
    private RolePermissionExtMapper rolePermissionExtMapper;

    @Override
    public void run(String... args) {
        Map<String, List<String>> rolePremissionMap = queryRolePermissions();
        rolePremissionMap.forEach((k, v) -> subjectRedisService.setRolePermission(k, v));
    }

    public Map<String, List<String>> queryRolePermissions() {
        List<RolePermissionExt> rolePermissions = rolePermissionExtMapper.selectRolePermissions(EnumConst.RoleType.JZFW);
        Map<String, List<String>> rolePermissionMap = new HashMap<>();
        for (RolePermissionExt rolePermission : rolePermissions) {
            String roleId = rolePermission.getRoleId();
            String permission = rolePermission.getPermissions();
            if (StringUtils.hasText(permission)) {
                List<String> list = rolePermissionMap.get(roleId);
                List<String> subList = Arrays.asList(permission.split(","));
                if (list == null) {
                    list = new ArrayList<>(subList);
                    rolePermissionMap.put(roleId, list);
                } else {
                    list.addAll(subList);
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Permissions: " + JacksonUtils.obj2Json(rolePermissionMap));
        }
        return rolePermissionMap;
    }


}
